#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
using PII = pair<int, int>;

const int N = 150005;
int n, m;
int h[N], e[N], ne[N], w[N], idx;
void add(int a, int b, int c)
{
    e[idx] = b; w[idx] = c; ne[idx] = h[a]; h[a] = idx++;
}

bool st[N];
int dist[N];

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> q;
    q.push({0, 1});
    while(q.size())
    {
        auto t = q.top(); q.pop();
        int distance = t.first, node = t.second;
        if(st[node]) continue;
        for(int i = h[node]; i != -1; i = ne[i])
        {
            int j = e[i];
            if(dist[j] > distance + w[i])
            {
                dist[j] = distance + w[i];
                q.push({dist[j], j});
            }
        }
        st[node] = true;
    }
    if(dist[n] == 0x3f3f3f3f) return -1;
    return dist[n];
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while(m--)
    {
        int a, b, c; cin >> a >> b >> c;
        add(a, b, c);
    }
    
    cout << dijkstra();
    
    return 0;
}